import { Repository , getRepository , FindManyOptions } from 'typeorm';
import { validate, ValidationError } from "class-validator";
import { Teams } from '../entity/teams';
import { BaseContext } from 'koa';

export default class TeamsControl {
    public static async saveTeam(teams: Array<Teams>) {
        const teamsRepository: Repository<Teams> = getRepository(Teams);
        const errors: ValidationError[] = await validate(teams);
        if(errors.length > 0) console.log(errors);
        else await teamsRepository.save(teams);
    }

    public static queryTeamAll(): Promise<Array<Teams>> {
        return new Promise(async (resolve,reject) => {
            const teamRepository: Repository<Teams> = getRepository(Teams);
            let teams: Teams[] = await teamRepository.find();
            resolve(teams);
        })
    }

    public static queryTeamById(id: string): Promise<Teams> {
        return new Promise(async (resolve,reject) => {
            const teamRepository: Repository<Teams> = getRepository(Teams);
            let team: Teams = await teamRepository.findOne(id);
            resolve(team);
        })
    }

    public static async getTeamsLists(ctx: BaseContext) {
        try {
            const TeamsRepository: Repository<Teams> = getRepository(Teams);
            let { pageSize , pageIndex , id , city , abbr , name , conference , code } = ctx.request.body;
            pageIndex = pageIndex && pageIndex > 0 ? pageIndex-1 : 0;
            pageSize = pageSize || 30;
            let queryOptions: FindManyOptions<Teams> = {
                relations: ["league"],
                order: {
                    id: "DESC"
                },
                where: {},
                skip: pageIndex*pageSize,
                take: pageSize,
                cache: true,
            }
            let where = {};
            if(id && id !== '') Object.assign({},where,{ id })
            if(city && city !== '') Object.assign({},where,{ cityEn: city })
            if(abbr && abbr !== '') Object.assign({},where,{ abbr })
            if(name && name !== '') Object.assign({},where,{ nameEn: name })
            if(conference && conference !== '') Object.assign({},where,{ conference })
            if(code && code !== '') Object.assign({},where,{ code })
            queryOptions.where = where;
            const [ teamsLists , total ] = await TeamsRepository.findAndCount(queryOptions);
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                teamsLists,
                total
            });
        } catch (error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);
        }
    }
}